﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;
using DuJianliang.ApplicationPlatform.UserPermission;

namespace DuJianliang.ApplicationPlatform.Proj5715.Process
{
    public partial class DispatchEdit : System.Web.UI.Page
    {
        ProcessDal processDal = new ProcessDal();

        private string FlowInstanceID
        {
            get
            {
                if (ViewState["FlowInstanceID"] != null)
                {
                    return ViewState["FlowInstanceID"].ToString();
                }
                else
                {
                    string flowInstanceID = Guid.NewGuid().ToString();
                    ViewState["FlowInstanceID"] = flowInstanceID;
                    return flowInstanceID;
                }
            }
            set
            {
                ViewState["FlowInstanceID"] = value;
            }
        }

        private string Source
        {
            get
            {
                object obj = ViewState["Source"];
                return obj != null ? obj.ToString() : string.Empty;
            }
            set
            {
                ViewState["Source"] = value;
            }
        }

        private string DispatchCode
        {
            get
            {
                if (ViewState["DispatchCode"] != null)
                {
                    return ViewState["DispatchCode"].ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                ViewState["DispatchCode"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserPermissionBll userPermissionBll = new UserPermissionBll();
                if (this.Source.ToLower().Equals("list") 
                    && !userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.AddDispatch))
                {
                    Response.Write("您没有权限使用该功能");
                    Response.End();
                    return;                    
                }

                this.FlowInstanceID = Request.QueryString["FlowInstanceID"];
                this.Source = Request.QueryString["Source"];
                BindMissileModel();
                this.BindGrid(this.FlowInstanceID);
                InitControl(this.FlowInstanceID);
                SetControlState(this.FlowInstanceID);
                
            }           
        }

        private void InitControl(string flowInstanceID)
        { 
            try
            {
                ProcessDal dal = new ProcessDal();
                DispatchOB dispatchOB = dal.GetDispatchByID(flowInstanceID);

                if (dispatchOB != null)
                {
                    this.DispatchCode = dispatchOB.DispatchCode;

                    txtDispatchCode.Text = dispatchOB.DispatchCode;

                    DateTime planCompletionDate = DateTime.Now;
                    if (DateTime.TryParse(dispatchOB.PlanCompletionDate, out planCompletionDate))
                    { 
                        txtPlanCompletionDate.Text = planCompletionDate.ToShortDateString();
                    }

                    foreach (ListItem item in ddlRepairType.Items)
                    {
                        item.Selected = false;
                    }
                    ddlRepairType.Items.FindByValue(dispatchOB.RepairType).Selected = true;

                    txtRemark.Text = dispatchOB.Remark;

                    switch (dispatchOB.DispatchState)
                    {
                        case "1":
                            txtDispatchState.Text = string.Format("已完成({0})", dispatchOB.DispatchCompletedDate);
                            break;
                        default:
                            txtDispatchState.Text = "未完成";
                            break;
                    }

                    foreach (ListItem item in ddlMissileModel.Items)
                    {
                        item.Selected = false;
                    }
                    ddlMissileModel.Items.FindByValue(dispatchOB.MissileModel).Selected = true;

                    txtIssueState.Text = string.IsNullOrWhiteSpace(dispatchOB.IssueState) ? "未下达" : "已下达";
                    BindIssueDept(dispatchOB.MissileModel);
                }                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void SetControlState(string flowInstanceID)
        {
            bool hasMainData = false;
            bool hasFlowData = false;
            bool flowCompleted = false; 
            bool fromFlow = false;
            bool fromList = false;
            bool dispatchIssue = false;
            bool dispatchCompleted = false;
            bool hasUnCompletedInDispatchMissile = false;          // 派工单中是否还有未完成工序的导弹
            bool hasUnCompletedInDispatchMissileProcess = false;   // 导弹中是否还有未完成或未检验的工序
            bool currentFlowStepIsFirstSetp = false;
            bool hasMissileCheckPermission = false;                // 是否有导弹检验的权限
            string flowEndOperation = string.Empty;

            ProcessDal processDal = new ProcessDal();
            UserPermissionBll userPermissionBll = new UserPermissionBll();
            DispatchOB dispatchOB = new DispatchOB();
            
            try
            {
                hasMissileCheckPermission = userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.MissileCheck);

                dispatchOB = processDal.GetDispatchByID(flowInstanceID);

                if (dispatchOB != null)
                {
                    hasMainData = true;
                    dispatchCompleted = dispatchOB.DispatchState.Equals("1");
                    hasUnCompletedInDispatchMissile = processDal.hasUnCompletedInDispatchMissile(dispatchOB.FlowInstanceID);

                    DataTable flowInstanceData = FlowHelper.GetFlowInstanceInfo(new Guid(this.FlowInstanceID));
                    if (flowInstanceData != null && flowInstanceData.Rows.Count > 0)
                    {
                        currentFlowStepIsFirstSetp = FlowHelper.CurrentFlowStepIsFirstSetp(flowInstanceData.Rows[0]["FlowID"].ToString()
                            ,this.FlowInstanceID);
                    }
                    

                    DataTable dataTable = FlowHelper.GetFlowInstanceInfo(new Guid(dispatchOB.FlowInstanceID));
                    if (dataTable != null && dataTable.Rows.Count > 0)
                    {
                        hasFlowData = true;

                        if(dataTable.Rows[0]["Completed"] != null)
                        {
                            string strCompleted = dataTable.Rows[0]["Completed"].ToString();

                            if (bool.TryParse(strCompleted, out flowCompleted) && flowCompleted)
                            {
                                if (dataTable.Rows[0]["OperationID"] != null)
                                {
                                    flowEndOperation = dataTable.Rows[0]["OperationID"].ToString();
                                }
                            }
                        }
                    }

                    dispatchIssue = dispatchOB.IssueState.ToLower().Equals("true");
                }

                if (this.Source.ToLower().Equals("list"))
                {                    
                    fromList = true;
                }
                else
                {
                    fromFlow = true;
                }
            }
            catch (Exception ex)
            {
                Helper.Instance.SetException(ex);
            }

            if (fromFlow)
            {
                txtDispatchCode.Enabled = false;
                txtPlanCompletionDate.Enabled = false;
                ddlRepairType.Enabled = false;
                ddlMissileModel.Enabled = false;
                txtRemark.Enabled = false;
                btnOK.Visible = false;
                btnMissileSelect.Visible = false;
                btnIssue.Visible = false;
                btnDispatchCompleted.Visible = false;
                btnCancel.Visible = false;
                GridView1.Columns[6].Visible = false;
                return;
            }

            if ((hasFlowData && !currentFlowStepIsFirstSetp) || dispatchCompleted)
            {
                txtDispatchCode.Enabled = false;
                txtPlanCompletionDate.Enabled = false;
                ddlRepairType.Enabled = false;
                ddlMissileModel.Enabled = false;
                txtRemark.Enabled = false;
            }
            else
            {
                txtDispatchCode.Enabled = true;
                txtPlanCompletionDate.Enabled = true;
                ddlRepairType.Enabled = true;
                ddlMissileModel.Enabled = true;
                txtRemark.Enabled = true;
            }

            // 确定按钮
            if ((hasFlowData && !currentFlowStepIsFirstSetp) || dispatchCompleted)
            {
                btnOK.Visible = false;
            }
            else
            {
                btnOK.Visible = true;
            }                        

            // 选择导弹按钮
            if ((hasFlowData && !currentFlowStepIsFirstSetp) || !hasMainData || dispatchCompleted)
            {
                btnMissileSelect.Visible = false;
            }
            else
            {
                btnMissileSelect.Visible = true;
            }

            // 下达按钮
            if (!flowCompleted || !flowEndOperation.Equals("2") || dispatchIssue || dispatchCompleted
                || !userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.DispatchIssue))
            {
                btnIssue.Visible = false;
            }
            else
            {
                btnIssue.Visible = true;
            }

            // 派工单完工按钮
            // 不显示的条件：有未完成工序的导弹 或 派工单已完成 或 派工单未下发
            if (hasUnCompletedInDispatchMissile || dispatchCompleted || !dispatchIssue)
            {
                btnDispatchCompleted.Visible = false;
            }
            else
            {
                btnDispatchCompleted.Visible = true;
            }            

            foreach (GridViewRow row in GridView1.Rows)
            {
                string missileModel = GridView1.DataKeys[row.RowIndex]["MissileModel"].ToString();
                string MissileCode = GridView1.DataKeys[row.RowIndex]["MissileCode"].ToString();

                Control btnExchange = row.FindControl("btnExchange");
                Control btnWastage = row.FindControl("btnWastage");
                Control btnDelete = row.FindControl("btnDelete");
                Control btnCompleted = row.FindControl("btnCompleted");
                Control btnProcess = row.FindControl("btnProcess");

                if (btnExchange != null)
                {
                    btnExchange.Visible = dispatchIssue;
                }

                if (btnWastage != null)
                {
                    btnWastage.Visible = dispatchIssue;
                }

                if (btnDelete != null)
                {
                    if ((hasFlowData && !currentFlowStepIsFirstSetp) || dispatchCompleted)
                    {
                        btnDelete.Visible = false;
                    }
                    else
                    {
                        btnDelete.Visible = true;
                    }
                }

                if (btnCompleted != null && btnCompleted.Visible)
                {
                    if (hasMissileCheckPermission)
                    {
                        if (!dispatchIssue || dispatchCompleted)
                        {
                            btnCompleted.Visible = false;
                        }
                        else
                        {
                            btnCompleted.Visible = true;
                        }
                    }
                    else
                    {
                        btnCompleted.Visible = false;
                    }
                }                

                if (btnProcess != null)
                {
                    btnProcess.Visible = dispatchIssue;
                }

                if(!processDal.InZaiXiuKu(missileModel, MissileCode))
                {
                    if (btnExchange != null)
                    {
                        btnExchange.Visible = false;
                    }

                    if (btnWastage != null)
                    {
                        btnWastage.Visible = false;
                    }

                    if (btnProcess != null)
                    {
                        btnProcess.Visible = false;
                    }
                }
            }
                       
                                
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            DispatchOB dispatchOB = new DispatchOB();
            dispatchOB.FlowInstanceID = this.FlowInstanceID;
            dispatchOB.DispatchCode = txtDispatchCode.Text.Trim();
            dispatchOB.RepairType = ddlRepairType.SelectedValue;
            dispatchOB.PlanCompletionDate = txtPlanCompletionDate.Text.Trim();
            dispatchOB.Remark = txtRemark.Text.Trim();
            dispatchOB.MissileModel = ddlMissileModel.SelectedValue;
            string datetime = DateTime.Now.ToString();
            dispatchOB.CreateDate = datetime;
            dispatchOB.ModifyDate = datetime;
            dispatchOB.CreateUser = Common.CurrentInfo.Instance.CurrentUser.UserName;
            dispatchOB.ModifyUser = Common.CurrentInfo.Instance.CurrentUser.UserName;

            try
            {
                ProcessDal dal = new ProcessDal();

                if (dal.HasDispatchCode(dispatchOB.DispatchCode, dispatchOB.FlowInstanceID))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('派工单号已存在');</script>");
                    return;
                }

                if (dal.GetDispatchByID(this.FlowInstanceID) != null)
                {
                    dal.Dispatch_UpdateBase(dispatchOB);
                }
                else
                {
                    dal.Dispatch_Insert(dispatchOB);
                }

                InitControl(this.FlowInstanceID);
                SetControlState(this.FlowInstanceID);
            }
            catch (System.Threading.ThreadAbortException)
            {
                // do nothing. 
                // Helper.ShowMessagePage 方法中使用了 Response.Redirect，该方法会引发 ThreadAbortException 异常
                // 参考http://support.microsoft.com/kb/312629/
            }
            catch (Exception ex)
            {
                Helper.Instance.SetException(ex);
            }
        }    

        private void BindGrid(string dispatchID)
        {
            ProcessDal dal = new ProcessDal();
            DataTable dataTable = dal.GetDispatchMissileTable(dispatchID);
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGrid(this.FlowInstanceID);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("DispatchList.aspx");
        }



        private void BindMissileModel()
        {
            //string sql = "SELECT distinct ItemCode FROM OITW";
            string sql = @"SELECT DISTINCT T0.ItemCode, T0.ItemCode + '(' + T2.ItemName + ')' AS Name FROM OITW T0 
                                JOIN OWHS T1 ON T0.WhsCode=T1.WhsCode
                                JOIN OITM T2 ON T2.ItemCode=T0.ItemCode
                                WHERE T1.U_CLASS2=202 AND T0.ONHAND>0";

            Database database = DatabaseFactory.CreateDatabase(Helper.Instance.ConnectionStringName_SBODB);
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@OperatorInfo", DbType.String, Common.CurrentInfo.Instance.CurrentUser.UserName);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            ddlMissileModel.DataSource = dataTable;
            ddlMissileModel.DataTextField = "Name";
            ddlMissileModel.DataValueField = "ItemCode";
            ddlMissileModel.DataBind();

            BindIssueDept(ddlMissileModel.SelectedValue);
        }

        protected void btnMissileSelect_Click(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("SelectMissile.aspx?dispatchID={0}&missilemodel={1}&level={2}", this.FlowInstanceID, ddlMissileModel.SelectedValue, ddlRepairType.SelectedValue));
        }

        protected void ddlMissileModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindIssueDept(ddlMissileModel.SelectedValue);
        }

        private void BindIssueDept(string missileMode)
        {
            lstBoxIssueWorkShop.Items.Clear();
            ProcessDal dal = new ProcessDal();
            DataTable dataTable = dal.GetIssueWorkShop(missileMode);

            foreach (DataRow dataRow in dataTable.Rows)
            {
                lstBoxIssueWorkShop.Items.Add(dataRow["DeptName"].ToString());
            }  
        }

        protected void btnIssue_Click(object sender, EventArgs e)
        {
            Helper helper = new Helper();
            Database database = DatabaseFactory.CreateDatabase();
            DbConnection dbConnection = null;
            DbTransaction dbTransaction = null;
            List<DbCommand> dbCommandList = new List<DbCommand>();
            ProcessDal dal = new ProcessDal();

            try
            {
                DataTable dispatchMissileTable = dal.GetDispatchMissileTable(this.FlowInstanceID);
                string firstProcessID = dal.GetFirstProcessID(ddlMissileModel.SelectedValue, ddlRepairType.SelectedValue);
                if (string.IsNullOrEmpty(firstProcessID))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('未找到匹配工序！');</script>"); 
                    return;
                }
                foreach (DataRow dataRow in dispatchMissileTable.Rows)
                {
                    DispatchMissileProcessOB dispatchMissileProcessOB = new DispatchMissileProcessOB();
                    dispatchMissileProcessOB.DispatchMissileProcessID = Guid.NewGuid().ToString();
                    dispatchMissileProcessOB.DispatchMissileID = dataRow["DispatchMissileID"].ToString();
                    dispatchMissileProcessOB.ProcessID = firstProcessID;
                    dispatchMissileProcessOB.ProcessSortNumber = "1";
                    dispatchMissileProcessOB.IsBeginRepair = "0";

                    DbCommand dbCommand = dal.GetDbCommand_DispatchMissileProcess_Insert(database, dispatchMissileProcessOB);
                    dbCommandList.Add(dbCommand);
                }

                DispatchOB dispatchOB = new DispatchOB();
                dispatchOB.FlowInstanceID = this.FlowInstanceID;
                dispatchOB.IssueDate = DateTime.Now.ToString();
                dispatchOB.IssueState = "1";
                dispatchOB.IssueUser = helper.CheckAndGetCurrentOperator();
                DbCommand dispatchDbCommand = dal.GetDbCommand_Dispatch_Issue(database, dispatchOB);
                dbCommandList.Add(dispatchDbCommand);

                dbConnection = database.CreateConnection();
                dbConnection.Open();
                dbTransaction = dbConnection.BeginTransaction();

                foreach (DbCommand dbCmd in dbCommandList)
                {
                    database.ExecuteNonQuery(dbCmd, dbTransaction);
                }

                dbTransaction.Commit();

                InitControl(this.FlowInstanceID);
                SetControlState(this.FlowInstanceID);
            }
            catch (System.Threading.ThreadAbortException)
            {
                // do nothing. 
                // Helper.ShowMessagePage 方法中使用了 Response.Redirect，该方法会引发 ThreadAbortException 异常
                // 参考http://support.microsoft.com/kb/312629/
            }
            catch (Exception ex)
            {
                if (dbTransaction != null)
                {
                    dbTransaction.Rollback();
                }
                helper.SetException(ex);
            }
            finally
            {
                if (dbConnection != null && dbConnection.State != ConnectionState.Closed)
                {
                    dbConnection.Close();
                }
            }

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var dal = new ProcessDal();
            string DispatchMissileID = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                    //工序
                case "process":
                    Response.Redirect(string.Format("ProcessList.aspx?flowInstanceID={0}&DispatchMissileID={1}", this.FlowInstanceID, DispatchMissileID));
                    break;

                    //删除
                case "del":                  
                    dal.DispatchMissile_Delete(DispatchMissileID);
                    BindGrid(this.FlowInstanceID);
                    break;

                case "complete":
                    dal.SetDispatchMissileComplete(DispatchMissileID);
                    BindGrid(this.FlowInstanceID);
                    break;
            }

            SetControlState(this.FlowInstanceID);
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string dispatchMissileID = GridView1.DataKeys[e.Row.RowIndex]["DispatchMissileID"].ToString();
                string missileCode = GridView1.DataKeys[e.Row.RowIndex]["MissileCode"].ToString();
                string missileModel = GridView1.DataKeys[e.Row.RowIndex]["MissileModel"].ToString();

                // 是否完工
                e.Row.Cells[4].Text = e.Row.Cells[4].Text.ToLower().Equals("true") ? "是" : "否";

                Button btnCompleted = e.Row.FindControl("btnCompleted") as Button;
                if (btnCompleted != null)
                {
                    btnCompleted.Visible = !e.Row.Cells[4].Text.Equals("是");

                    if (btnCompleted.Visible && processDal.hasUnCompletedInDispatchMissileProcess(dispatchMissileID))
                    {
                        btnCompleted.Visible = false;
                    }
                }

                Button btnArriveShow = e.Row.FindControl("btnArriveShow") as Button;
                if (btnArriveShow != null)
                {
                    string url = string.Format("MissileArriveShow.aspx?itemCode={0}&distNumber={1}", missileModel, missileCode);
                    btnArriveShow.Attributes.Add("onclick", string.Format("showPage('{0}','1000px','620px');", url));
                }
                                
                Button btnExchange = e.Row.FindControl("btnExchange") as Button;
                if (btnExchange != null)
                {
                    string url = string.Format("ExchangePartView.aspx?flowInstanceID={0}&DispatchMissileID={1}", this.FlowInstanceID, dispatchMissileID);
                    btnExchange.Attributes.Add("onclick", string.Format("showPage('{0}','1000px','600px');", url));
                }

                Button btnWastage = e.Row.FindControl("btnWastage") as Button;
                if (btnWastage != null)
                {
                    string url = string.Format("ProcessWastage.aspx?DispatchCode={0}&MissileCode={1}", this.DispatchCode, missileCode);
                        
                    btnWastage.Attributes.Add("onclick", string.Format("showPage('{0}','800px','600px');", url));
                }

                // 计算剩余寿命
                string strInDate = GridView1.DataKeys[e.Row.RowIndex]["InDate"].ToString();
                string strLifeTime = GridView1.DataKeys[e.Row.RowIndex]["RemainingLife"].ToString();

                DateTime inDate = DateTime.Now;
                if (!DateTime.TryParse(strInDate, out inDate))
                {
                    return;
                }

                int lifeTime = 0;
                if (!int.TryParse(strLifeTime, out lifeTime))
                {
                    return;
                }

                TimeSpan timeSpan = DateTime.Now.Subtract(inDate);
                double temp = timeSpan.Days / 30.00;
                double newLifeTime = lifeTime - temp;
                if (newLifeTime < 0)
                {
                    newLifeTime = 0;
                }
                e.Row.Cells[3].Text = Math.Round(newLifeTime, 2).ToString();
            }
        }

        protected void btnDispatchCompleted_Click(object sender, EventArgs e)
        {
            Database database = DatabaseFactory.CreateDatabase();
            ProcessDal processDal = new ProcessDal();
            processDal.SetDispatchComplete(database, this.FlowInstanceID);
            InitControl(this.FlowInstanceID);
            SetControlState(this.FlowInstanceID);
        }        
    }
}